<template>
  <div class="_p10 _flex-y _flex-space _wrapper">
    <div class="_wrapper-x _background-3 _font-title _p5 _radius-5p _flex">
      串口调试
      <el-button type="primary" @click="openSelectSerial()">选择串口</el-button>
    </div>
    <div class="_cart _p10 _flex-item-1 _wrapper-x">
      <div v-if="!serialStatus">不支持串口操作，请更换浏览器</div>
      <div v-else-if="!serialPort">
        <el-button type="primary" @click="openSelectSerial()"
          >选择串口</el-button
        >
      </div>
      <div v-else class="_wrapper _flex-y">
        <div class="_flex _flex-space-x _wrapper-x _flex-start">
          <div class="_nowrap">执行产品：</div>
          <el-select
            v-model="currProCode"
            placeholder="请选择产品"
            style="width: 200px"
          >
            <el-option
              :label="item.name"
              :value="item.code"
              v-for="item in products"
              :key="item.code"
            ></el-option>
          </el-select>
          <el-input
            v-if="currProCode == 'fmkj-site-to-show'"
            v-model="siteCode"
            placeholder="请输入基站编码"
            style="width: 200px"
          ></el-input>
          <div class="_nowrap">波特率：</div>
          <el-input
            v-model="baudRate"
            placeholder="请输入波特率"
            style="width: 200px"
          ></el-input>
          <!-- <el-button type="primary" @click="openSerial()">打开串口</el-button> -->
          <el-button type="primary" @click="runProduct()">运行产品</el-button>
        </div>
        <div
          v-if="isOpen"
          class="_flex _flex-dis-2 _flex-center _text-a-c _flex-item-1 _wrapper-x"
        >
          <div class="_p10 _wrapper-y _flex-y">
            <div>发送内容</div>
            <div
              class="_p10 _m-t-10 _background-3 _radius-5p _flex-item-1 _wrapper-x _box-scroll _over-scroll-hidden"
            >
              <div
                v-for="(item, _index) in sendList"
                :key="_index"
                class="_wrapper-x _text-a-l"
              >
                {{ $tool.dateStr(item.time) }}:{{ item.msg }}
              </div>
            </div>
            <div class="_wrapper-x _flex _m-t-10 _flex-space-x">
              <el-input
                v-model="sendMsg"
                placeholder="请输入发送内容"
              ></el-input>
              <el-button type="primary" @click="sendData()">发送</el-button>
            </div>
          </div>
          <div class="_p10 _wrapper-y _flex-y">
            <div>接收内容</div>
            <div
              class="_p10 _m-t-10 _background-3 _radius-5p _flex-item-1 _wrapper-x _box-scroll _over-scroll-hidden"
            >
              <div
                v-for="(item, _index) in receiveList"
                :key="_index"
                class="_wrapper-x _text-a-l"
              >
                {{ $tool.dateStr(item.time) }}:{{ item.msg }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import toolSerial from "@/tool/tool-serial";
import { initDefault } from "@/tool/tool-mqtt";
import tool212 from "@/tool/tool-212";

// 运行产品
let mqttApi;

const textEncoder = {
  textDecoder: new TextDecoder(),
  textEncoder: new TextEncoder(),
  decode(msg) {
    return this.textDecoder.decode(msg);
  },
  encode(msg) {
    return this.textEncoder.encode(msg);
  },
};

function checksum(data) {
  let checksum = 0;
  for (let i = 0; i < data.length; i++) {
    checksum += data.charCodeAt(i);
  }
  return checksum & 0xff;
}

function buildShowMsg(val, code) {
  val = val.substring(0, 5);
  let length = (val.length + 6).toString().padStart(4, "0");
  let msg = `KLB000100000057${length}${code}0000${val}KLE`;
  msg += checksum(msg).toString(16).toUpperCase();
  return msg;
}

export default {
  data() {
    return {
      serialStatus: toolSerial.serialStatus,
      serialPort: undefined,
      isOpen: false,
      baudRate: 9600,
      sendList: [],
      receiveList: [],
      sendMsg: "",
      products: [
        {
          code: "fmkj-default",
          name: "富铭科技-默认",
        },
        {
          code: "fmkj-site-to-show",
          name: "富铭科技-数据推送大屏",
          baudRate: 57600,
        },
      ],
      currProCode: "fmkj-default",
      siteCode: "41010501G00002",
    };
  },
  mounted() {},
  methods: {
    async openSelectSerial() {
      this.serialPort = await toolSerial.openSelectSerial();
    },
    async openSerial() {
      this.isOpen = await toolSerial.openSerial((msg) => {
        this.receiveList.push({
          msg: textEncoder.decode(msg),
          time: new Date(),
        });
      }, this.baudRate);
    },
    async sendData(msg) {
      msg = msg || this.sendMsg;
      this.sendList.push({
        msg,
        time: new Date(),
      });
      toolSerial.syncSendData(textEncoder.encode(msg));
    },
    async closeSerial() {
      toolSerial.closeSerial();
    },
    async runProduct() {
      let product = this.products.find(
        (item) => item.code === this.currProCode
      );
      if ("fmkj-site-to-show" === this.currProCode) {
        this.baudRate = product.baudRate;
        // 打开端口
        await this.openSerial();

        mqttApi = mqttApi || initDefault();
        mqttApi.unsubscribeAll();
        mqttApi.subscribe("/com-server/212/msg/" + this.siteCode, (msg) => {
          let data212 = tool212.parse212Data(msg.toString());

          // 流量
          let f10001 = data212._cpData["f10001-Rtd"];
          // 液位
          let f10011 = data212._cpData["f10011-Rtd"];
          // 雨量
          let f11001 = data212._cpData["f11001-Rtd"];

          if (f10001) {
            this.sendData(buildShowMsg(f10001, "14"));
          }
          if (f10011) {
            this.sendData(buildShowMsg(f10011, "15"));
          }
          if (f11001) {
            this.sendData(buildShowMsg(f11001, "16"));
          }
        });
      } else {
        // 打开端口
        await this.openSerial();
      }
    },
  },
};
</script>
<style></style>
